/**
 *
 */
package com.newture.lxz.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.newture.lxz.constant.Constant;
import com.newture.lxz.db.mapper.LdOrderMapper;
import com.newture.lxz.db.model.*;
import com.newture.lxz.errors.AppException;
import com.newture.lxz.generator.output.Column;
import com.newture.lxz.pvg.Pvg;
import com.newture.lxz.services.IGoodsSrv;
import com.newture.lxz.services.IOrderItemSrv;
import com.newture.lxz.services.IOrderSrv;
import com.newture.lxz.services.IPaySrv;
import com.newture.lxz.util.SNKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author xiao.hu
 *
 */
@Service("CommonOrderSrv")
public class CommonOrderSrv {
    @Autowired
    IPaySrv paySrv;
    @Autowired
    IOrderSrv orderSrv;
    @Autowired
    IGoodsSrv iGoodsSrv;
    @Autowired
    IOrderItemSrv orderItemSrv;

    @Resource
    LdOrderMapper ldOrderMapper;


    /**
     * 通过订单号查找订单信息
     * @param orderSN
     * @return
     */
    public LdOrder findBySN(String orderSN, String[] keys) {

        LdOrderExample example = new LdOrderExample();
        LdOrderExample.Criteria criteria = example.createCriteria();
        criteria.andSnEqualTo(orderSN);
        criteria.andIsDeletedEqualTo(Constant.NO);

        example.setDynamicColumns(keys);
        List<LdOrder> list = ldOrderMapper.selectByExample(example);
        if(list.isEmpty()) {
            throw new AppException(com.newture.lxz.errors.Errors.NO_RECORD_FOUND_BY_ID.name(),
                    String.format("ID is %s", orderSN), "No record found in CourtAddressSrv.findById()");
        }

        if(list.size() > 1) {
            throw new AppException(com.newture.lxz.errors.Errors.MORE_THAN_ONE_RECORDS_FOUND.name(),
                    String.format("ID is %s", orderSN), "More than one record found in CourtAddressSrv.findById()");
        }

        return list.get(0);
    }



    public String createOrder(List<Map<String, Object>> orderItems, String process, String remark,
                              String recipientAddress) {
        TotalPriceCounter oTotalPriceCounter = new TotalPriceCounter();
        oTotalPriceCounter.setTotalPrice(new BigDecimal(0));
        /*第一步，新增order记录*/
        LdOrder targerOrder = this.addOrder(oTotalPriceCounter, process, recipientAddress, remark);

        /*第二步，新增orderItems记录，并计算绑定在商品上的折扣*/
        this.addOrderItemsWithGoodsDiscounts(targerOrder, orderItems, oTotalPriceCounter);

        /*第五步，新增支付记录，状态为待支付*/
        LdPay ldPay = new LdPay();
        ldPay.setOrderSn(targerOrder.getSn());
        ldPay.setSn(SNKit.nextId());
        paySrv.insert(ldPay);

        return targerOrder.getSn();
    }

    /**
     * 新增一条Order记录
     * @return
     */
    private LdOrder addOrder(TotalPriceCounter oTotalPriceCounter, String process, String recipientAddress, String remark) {
        LdOrder ldOrder = new LdOrder();
        BigDecimal totalPrice = oTotalPriceCounter.getTotalPrice();
        BigDecimal costZ = new BigDecimal(0.00);
        Integer cusId = Pvg.getPvg().getUserId().intValue();

        ldOrder.setTotalPrice(totalPrice);
        ldOrder.setCustomerId(cusId);
        ldOrder.setStatus("payment_pending");
        ldOrder.setPaymentStatus("unpaid");
        ldOrder.setShippingStatus("unshipped");
        ldOrder.setProcess(process);
        ldOrder.setAddress(recipientAddress);
        ldOrder.setRemark(remark);
        ldOrder.setGmtModified(LocalDateTime.now());
        ldOrder.setExpressCost(costZ);
        ldOrder.setPayments(totalPrice);
        ldOrder.setPaymentsDescription("");
        ldOrder.setIsPrivacyClear("n");
        String newSN = SN.nextOrderId();
        ldOrder.setSn(newSN);
        int newOrderId = orderSrv.insert(ldOrder);
        return orderSrv.findById(newOrderId,
                new String[]{Column.ID, Column.VERSION, Column.LD_ORDER.SN});
    }


    /**
     * 新增orderItems记录
     * @param targerOrder
     * @param orderItems
     */

    private void addOrderItemsWithGoodsDiscounts(LdOrder targerOrder, List<Map<String, Object>> orderItems, TotalPriceCounter oTotalPriceCounter) {
        BigDecimal totalPrice = oTotalPriceCounter.getTotalPrice();
        for(Map<String, Object> map : orderItems) {
            long goodsId = (long)map.get(Column.ID);
            LdGoods goods = iGoodsSrv.findById(goodsId, new String[]{
                    Column.LD_GOODS.NAME,
                    Column.LD_GOODS.PRICE,
                    Column.LD_GOODS.SN
            });

            String orderItemSN = SN.nextOrderItemId();
            LdOrderItem ldOrderItem = new LdOrderItem();
            ldOrderItem.setOrderSn(targerOrder.getSn());
            ldOrderItem.setSn(orderItemSN);
            ldOrderItem.setGoodsName(goods.getName());
            ldOrderItem.setGoodsSn(goods.getSn());
            ldOrderItem.setGoodsPrice(goods.getPrice());

            /* 新增订单项 */
            orderItemSrv.insert(ldOrderItem);
        }

        oTotalPriceCounter.setTotalPrice(totalPrice);
    }



        final class TotalPriceCounter {
        private BigDecimal totalPrice;

        public BigDecimal getTotalPrice() {
            return totalPrice;
        }

        public void setTotalPrice(BigDecimal totalPrice) {
            this.totalPrice = totalPrice;
        }
    }
}
